﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ESOL.Common.Entity;
using ESOL.Business.Inv;
using ESOL.WinUI.UICommon;
using ESOL.Business.Mst;
using ESOL.Common;

namespace ESOL.WinUI.Inv
{
    public partial class frmMaintainDispatchOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public InvDispatchOrderEntity SelectedDispatchOrder { get; set; }
        private List<InvDispatchItemEntity> DeleteList = new List<InvDispatchItemEntity>();
        private List<SalesProdPlanApplicationItemEntity> mListApplicationItem;
        #endregion

        #region Constructor
        public frmMaintainDispatchOrder()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {

            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "IDO", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbOrderType, "IDT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit1, "UNIT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit2, "UNIT", true);

            //UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPACKAGE_TYPE, "PT", true);
            //UICommon.UICommonFunctions.BindGridComboboxByLocation(colLOCATION_CODE, "", true);
        }
        private void BindDataGridDetail()
        {
            if (SelectedDispatchOrder == null)
            {
                gvDetail.DataSource = null;
                return;
            }
            DataSet ds = InvDispatchOrderBs.GetDataSetByDispatchOrderId(SelectedDispatchOrder.DispatchOrderId, SelectedDispatchOrder.OrderType);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvDetail.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvDetail.DataSource = dt;


            DeleteList = new List<InvDispatchItemEntity>();
        }
        private void SetFields()
        {

            BindDataGridDetail();
            if (SelectedDispatchOrder == null)
            {
                return;
            }
            cmbOrderType.SetSelectedValue(SelectedDispatchOrder.OrderType);
            cmbStatus.SetSelectedValue(SelectedDispatchOrder.Status);
            txtOrderCode.Text = SelectedDispatchOrder.OrderCode;
            if (SelectedDispatchOrder.OrderDate.ToString("yyyy-MM-dd") != "0001-01-01" && SelectedDispatchOrder.OrderDate.ToString("yyyy-MM-dd") != "1900-01-01")
            {
                dtpOrderDate.EditValue = Convert.ToDateTime(SelectedDispatchOrder.OrderDate);
            }

            MstPersonEntity orderPerson = MstPersonBs.GetMstPersonByID(SelectedDispatchOrder.OrderPerson);

            if (SelectedDispatchOrder.RelatedOrder != null)
            {
                #region 销售出库
                if (SelectedDispatchOrder.OrderType == "IDT01")
                {

                }
                #endregion
                #region 领料出库
                if (SelectedDispatchOrder.OrderType == "IDT02")
                {
 
                }
                #endregion
                #region 报废出库
                if (SelectedDispatchOrder.OrderType == "IDT03")
                {

                }
                #endregion
                #region 盘亏出库
                if (SelectedDispatchOrder.OrderType == "IDT04")
                {
                    InvCheckingPlanEntity ic = InvCheckingPlanBs.GetCheckingPlanByID(SelectedDispatchOrder.RelatedOrder);
                    if (ic == null)
                    {
                        MessageBox.Show("找不到相关单据！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    txtRelatedOrder.Text = ic.CheckingPlanCode;
                    txtRelatedOrder.Tag = ic;
                }
                #endregion
                #region 维修出库
                if (SelectedDispatchOrder.OrderType == "IDT05")
                {

                }
                #endregion

            }
            txtRemark.Text = SelectedDispatchOrder.Remark;

            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedDispatchOrder.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedPerson, SelectedDispatchOrder.ApprovedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifyDate, SelectedDispatchOrder.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifyPerson, SelectedDispatchOrder.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtCreatDate, SelectedDispatchOrder.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatPerson, SelectedDispatchOrder.CreatedBy);
        }
        private void SetEntity()
        {
            if (ThisActionType == ActionType.New)
            {
                SelectedDispatchOrder = new InvDispatchOrderEntity();
            }
            if (dtpOrderDate.EditValue!=null)
            {
                SelectedDispatchOrder.OrderDate = Convert.ToDateTime(dtpOrderDate.EditValue);
            }

            if (cmbOrderType.SelectedValue != null && cmbOrderType.SelectedValue.ToString().Trim() != "")
            {
                SelectedDispatchOrder.OrderType = cmbOrderType.SelectedValue.ToString().Trim();
            }

            SelectedDispatchOrder.RelatedOrder = txtRelatedOrder.Text;
            SelectedDispatchOrder.Remark = txtRemark.Text;
            SelectedDispatchOrder.OrderCode = txtOrderCode.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedDispatchOrder.Status = "IDO01";
                SelectedDispatchOrder.DispatchOrderId = Guid.NewGuid().ToString();
                SelectedDispatchOrder.CreatedDate = DateTime.Now;
                SelectedDispatchOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedDispatchOrder.LastModifiedDate = DateTime.Now;
                SelectedDispatchOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtOrderCode.Text))
            {
                MessageBox.Show("申请单号不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(cmbOrderType.Text))
            {
                MessageBox.Show("出库类型不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpOrderDate.EditValue ==null)
            {
                MessageBox.Show("出库单不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gvDetail.DataSource == null || gridView1.RowCount == 0)
            {
                MessageBox.Show("申请单明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (ThisActionType == ActionType.Approve)
            {
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    if (string.IsNullOrEmpty(dt.Rows[i]["WAREHOUSE_CODE"].ToString()))
                    {
                        MessageBox.Show("列表第" + i.ToString() + "行，仓库编码不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
            }
            return true;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = InvDispatchOrderBs.SaveDispatchOrder(true, SelectedDispatchOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = InvDispatchOrderBs.SaveDispatchOrder(false, SelectedDispatchOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    SelectedDispatchOrder.ApprovedDate = DateTime.Now;
                    SelectedDispatchOrder.ApprovedBy = CommonParameter.CurrentUser.UserId;
                    // bool isSuccessful = InvDispatchOrderBs.SaveApproveDispatch(SelectedDispatchOrder,dt);
                    if (!InvDispatchOrderBs.SaveApproveDispatch(SelectedDispatchOrder, dt))
                    {
                        MessageBox.Show("出库失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        private void frmMaintainDispatchOrder_Load(object sender, EventArgs e)
        {
            BindComboBox();
            SetFields();
        }
        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_SaveNew()
        {

        }
        protected override void Click_Approve()
        {
            if (SelectedDispatchOrder == null)
            {
                return;
            }
            SelectedDispatchOrder.Status = "IDO03";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Reject()
        {
            if (SelectedDispatchOrder == null)
            {
                return;
            }
            SelectedDispatchOrder.Status = "IDO04";
            bool successful = InvDispatchOrderBs.UpdateInvDispatchOrder(SelectedDispatchOrder);
            if (successful)
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void repProductCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

        private void repWareHouseCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
              frmMaintainWareHouseQuery frm = new frmMaintainWareHouseQuery();
              if (frm.ShowDialog() == DialogResult.OK)
              {
                  drSelectedDetail["WAREHOUSE_CODE"] = frm.SelectedWarehouse.WarehouseCode;
                  drSelectedDetail["WAREHOUSE_NAME"] = frm.SelectedWarehouse.WarehouseName;
                  DataTable dt = MstLocationBs.GetLocationByWarehouseCode(frm.SelectedWarehouse.WarehouseCode);
                  if (dt!=null&& dt.Rows.Count > 0)
                  {
                      drSelectedDetail["LOCATION_CODE"] = dt.Rows[0]["LOCATION_CODE"].ToString();
                  }
              }
        }
        private DataRow drSelectedDetail;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelectedDetail = gridView1.GetDataRow(e.FocusedRowHandle);
        }
        private void ItemAdd_Click(object sender, EventArgs e)
        {
            if (gvDetail.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvDetail.DataSource;
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
        }

        private void ItemDelete_Click(object sender, EventArgs e)
        {
            if (gvDetail.DataSource == null)
            {
                return;
            }
            if (drSelectedDetail == null)
            {
                return;
            }
            if (drSelectedDetail.RowState != DataRowState.Added)
            {
                InvDispatchItemEntity entity = new InvDispatchItemEntity(drSelectedDetail);
                DeleteList.Add(entity);
            }
            DataTable dt = gvDetail.DataSource as DataTable;
            dt.Rows.Remove(drSelectedDetail);

        }

        private void repLocation_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainLocationQuery frm = new frmMaintainLocationQuery();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                drSelectedDetail["LOCATION_CODE"] = frm.SelectLocation.LocationCode;
                drSelectedDetail["LOCATION_ID"] = frm.SelectLocation.LocationId;
            }
        }




    }
}